<template>
    <div class="w-full">
        <a-select v-if="!props.readonly" @change="getVal" @click="openPanel" :disabled="props.disabled" :allowClear="false" :open="false" class="w-full" v-model:value="name" :placeholder="props.placeholder">
        </a-select>
        <a-textarea v-else :value="name" placeholder="-" auto-size />
    </div>
</template>
<script setup>
const emits = defineEmits(['update:value', 'update:name', 'change'])
const props = defineProps({
    formRef: Object,
    value: String,
    name: String,
    type: {
        type: String,
        default: 'USER',
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    placeholder: {
        type: String,
        default: '请选择',
    },
    readonly: {
        type: Boolean,
        default: false,
    },
})
const state = reactive({
    value: '',
    name: '',
})

const inputVal = item => {
    if (item === undefined) {
        emits('update:value', undefined)
        emits('update:name', undefined)
    } else {
        emits('update:value', state.value)
        emits('update:name', state.name)
    }
    emits('change', item)
}

function getVal(val) {
    if (val === undefined) {
        inputVal()
    }
}

const openPanel = () => {
    if (props.disabled) return
    if (window.appType === '浏览器') {
        message.warning('请在钉钉客户端操作！')
        return
    }
    if (props.disabled) return
    if (props.type === 'USER') {
        dd.biz.contact
            .complexPicker({
                multiple: false,
                users: props.value,
                corpId: window.corpId,
                pickedUsers:[props.value], 
            })
            .then(res => {
                let userList = res.users
                if (userList && userList.length) {
                    state.value = userList[0].emplId
                    state.name = userList[0].name
                    inputVal(userList)
                }
            })
    } else {
        dd.biz.contact
            .departmentsPicker({
                title: '选择部门（单选）',
                corpId: window.corpId,
                pickedDepartments: [props.value],
                multiple: false,
            })
            .then(res => {
                if (res.departments && res.departments.length) {
                    state.value = res.departments[0].id
                    state.name = res.departments[0].name
                    inputVal(res.departments[0])
                }
            })
    }
}
watch(
    () => props.name,
    (newVal, oldVal) => {
        state.name = newVal
    },
    { deep: true, immediate: true }
)
watch(
    () => props.value,
    (newVal, oldVal) => {
        state.value = newVal
    },
    { deep: true, immediate: true }
)

defineExpose({})
const { value, name } = toRefs(state)
</script>

